﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Cxuu.Web.Authorize;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PetaPoco;
using System.IO;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin
{
    [Area("Admin")]
    [Authorize]
    public class AttmentController : Base
    {
        private readonly LoginUtil _LoginUtil;
        private readonly LogService _logService;
        private readonly AttmentService _attment;
        public AttmentController(LoginUtil LoginUtil,LogService logService, AttmentService attmentService)
        {
            _LoginUtil = LoginUtil;
            _logService = logService;
            _attment = attmentService;
        }

        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.Attment_Index)]
        public async Task<IActionResult> IndexAsync(int page = 1, int limit = 15, int json = 0)
        {
            if (json == 1)
            {
                UserInfo adminUser = await _LoginUtil.UserInfoAsync();
                int adminUid = adminUser.Gid != 1 ? adminUser.UserId : 0;//超级管理员显示全部数据
                Page<ViewAttment> list = await _attment.GetPageListAsync(page, limit, adminUid);
                return Json(new { code = 0, data = list.Items, count = list.TotalItems });
            }
            return View();
        }
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.Attment_AddOrEdit)]
        public async Task<IActionResult> AddOrEditAsync()
        {
            ViewBag.uid = await _LoginUtil.LoginUserId();
            return View();
        }

        [HttpPost]
        [ActionPermissionFilter(Permission = PermissionKeys.Attment_Delete)]
        [Log(Name = "删除上传文件")]
        public async Task<IActionResult> Delete(int id)
        {
            Attment attment = await _attment.GetAsync(id);
            string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot") + "\\" + attment.Url;
            if (FileUtility.FileExists(filePath))
            {
                FileUtility.FileDel(filePath);
            }
            if (await _attment.DeleteByPriKeyAsync(id) > 0)
            {
                return Json(new { status = 1, msg = "删除上传文件 id:" + id });
            }
            else
                return Json(new { status = 0, msg = "删除上传文件 id:" + id });
        }
    }
}
